package cc.ycws.web.controller;

import cc.ycws.core.util.ImageUtils;
import cc.ycws.core.util.ImgCompress;
import cc.ycws.core.util.ListString;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class ShowUserInforMationController {

    Logger logger = Logger.getLogger(ShowUserInforMationController.class);
    String czy = "/home/apache-tomcat-7.0.47/webapps/image/czy/";


    private static String access_token() {
        String accessToken = "";
        String GET_URL = "https://openapi.colourlife.com/v1/authms/auth/app?ts=1514512059"
                + "&corp_uuid=a8c58297436f433787725a94f780a3c9"
                + "&app_uuid=ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED"
                + "&signature=dfda1da6ddcba5e0d5301dff6ea61a3c"
                + "&timestamp=1514512059"
                + "&sign=ab898f60038dada455d4e40e0ceec82c"
                + "&appID=ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED";
        try {
            URL url = new URL(GET_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            connection.disconnect();
            JSONObject json = JSONObject.parseObject(sb.toString());
            JSONObject content = json.getJSONObject("content");
            accessToken = content.getString("accessToken");
            System.out.println("accessToken" + accessToken);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 展示用户信息
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = "/information", method = RequestMethod.POST)
    public String information(@RequestParam(value = "filepath", required = false) MultipartFile file, HttpServletRequest request, ModelMap ModelMap) throws Exception {
        String nickname = request.getParameter("nickname");
        String mobile = request.getParameter("mobile");
        String community_name = request.getParameter("community_name");
        String openid = request.getParameter("openid");
        String community_uuid = request.getParameter("community_uuid");
        //转码处理
        nickname = java.net.URLDecoder.decode(nickname, "UTF-8");
        community_name = java.net.URLDecoder.decode(community_name, "UTF-8");
        //参数输出
        logger.info("nickname=" + nickname + "\t mobile=" + mobile + "\t community_name=" + community_name + "\t openid=" + openid + "\t community_uuid" + community_uuid);
        //获取彩之云鉴权参数
        String access_token = access_token();
        //获取彩之云用户参数
        String GET_URL = "https://openapi.colourlife.com/v1/resourcems/building/search?ts=1514512235"
                + "&sign=cf55aec38db3da63c8a36ebb42ba6610"
                + "&appID=ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED"
                + "&token=" + access_token
                + "&pageIndex=1"
                + "&pageSize=10"
                + "&communityUuid="
                + community_uuid;
        List<String> list = ListString.list1(GET_URL);
        String fileName = file.getOriginalFilename();
        String str = fileName.substring(fileName.indexOf("."));
        Date data = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String newData = dateFormat.format(data);
        String name = newData + str;
        File targetFile = new File(czy + name);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            logger.info("前端请求图片名:" + name);
            BufferedImage src = ImageIO.read(targetFile);
            BufferedImage bi = null;
            //图片存在
            if (src != null) {
                //获取图片旋转角度
                int angel = ImageUtils.getRotateAngleForPhoto(czy, name);
                if (angel == 0) {
                    //图片正常，不处理图片
                    bi = src;
                    //图片压缩
                    ImgCompress.setFile(czy + name);
                    logger.info("开始：" + new Date().toLocaleString());
                    ImgCompress imgCom = new ImgCompress(czy + name);
                    imgCom.resizeFix(400, 400);
                    logger.info("结束：" + new Date().toLocaleString());
                } else {
                    //图片被翻转，调整图片
                    int src_width = src.getWidth(null);
                    int src_height = src.getHeight(null);
                    Rectangle rect_des = ImageUtils.CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);

                    bi = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2 = bi.createGraphics();

                    g2.translate((rect_des.width - src_width) / 2,
                            (rect_des.height - src_height) / 2);
                    g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

                    g2.drawImage(src, null, null);
                }
            } else {
                //图片不存在
                logger.info("图片：" + name + "为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelMap.addAttribute("uploadImg", "https://wwl.ycws.cc/image/czy/" + name);
        ModelMap.addAttribute("nickname", nickname);
        ModelMap.addAttribute("mobile", mobile);
        ModelMap.addAttribute("address", community_name);
        ModelMap.addAttribute("openid", openid);
        ModelMap.addAttribute("list", list);
        return "csh/userInformation";
    }
}
